package com.v1.video.engine;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.google.gson.Gson;
import com.iss.view.common.ToastAlone;
import com.v1.video.Constant;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.LoginUserInfoEntity;
import com.v1.video.domain.MyloginVcodeOfForgetEntity;
import com.v1.video.domain.ResultInfoEntity;
import com.v1.video.domain.StarUserOfTickEntity;
import com.v1.video.domain.UserHeadModifyEntity;
import com.v1.video.domain.UserInfo4_4;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.ParamList;
import com.v1.video.httpmanager.ParamList.Parameter;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.pay.MD5;
import com.v1.video.util.Logger;
import com.v1.video.util.SDCardFileUtils;
import com.v1.video.util.Utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class RequestEngine {

	public final String TAG = "RequestEngine";

	/***
	 * 登录
	 * 
	 * @param context
	 * @param username
	 * @param pwd
	 * @param handler
	 * @param type
	 * @param typefail
	 */
	public void getLoginInfo(final Activity context, String username,
			String pwd, final Handler handler, final int type,
			final int typefail) {
		String url = V1VideoHttpApi.GET_INFO_TO_LOGIN() + "&devid=" + Constant.DEVICEID;

		Logger.i(TAG, "登录Url =" + url);
		ParamList list = new ParamList();
		list.add(new Parameter("username", username));
		list.add(new Parameter("password", pwd));
		list.add(new Parameter("lastLoginIp", ""));
		Map<String, String> map = Utils.getLongitudeAndLatitude(context);
		if (map != null) {
			list.add(new Parameter("longitude", map.get("longitude")));
			list.add(new Parameter("latitude", map.get("latitude")));
		} else {
			list.add(new Parameter("longitude", ""));
			list.add(new Parameter("latitude", ""));
		}
		list.add(new Parameter("baseStation", ""));
		list.add(new Parameter("cellIdentity", ""));
		list.add(new Parameter("IMEI", Constant.DEVICEID));
		list.add(new Parameter("IMSI", Utils.getSubscriberId(context)));
		RequestManager.getInstance().postRequest(context, url, list,
				LoginUserInfoEntity.class, 0, "UserRegisterActivity",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());
						LoginInfo loginInfo = LoginInfo.getInstance();
						if (object != null) {
							LoginUserInfoEntity entity = (LoginUserInfoEntity) object;
							com.v1.video.domain.BaseEntity.Header header = entity
									.getHeader();
							if (header == null) {
								ToastAlone.showToast(context, "未知错误",
										Toast.LENGTH_SHORT);
								Message msg = handler.obtainMessage();
								msg.what = typefail;
								handler.sendMessage(msg);
								return;
							} else if (!header.getStatus().equals("1")) {
								Message msg = handler.obtainMessage();
								msg.what = typefail;
								handler.sendMessage(msg);
								ToastAlone.showToast(context,
										header.getMessage(), Toast.LENGTH_SHORT);
								return;
							} else if (header.getStatus().equals("1")) {
								if (entity.getBody() != null) {

									if (entity.getBody().getStatus()
											.equals("1")) {
										UserInfo4_4 userInfo = entity.getBody()
												.getData();
										loginInfo.setUserId(userInfo.getUid());
										loginInfo.setUserName(userInfo
												.getUsername());
										loginInfo.setLoginName(userInfo
												.getUsername());
										loginInfo.setNickName(userInfo
												.getNickname());
										loginInfo.setUserImg(userInfo
												.getPicture());
										loginInfo.setDetail(userInfo
												.getSignature());
										loginInfo.setSex(userInfo.getGender());
										loginInfo.setRegion(userInfo
												.getAddress());
										loginInfo.setState(userInfo.getStatus());
										loginInfo.setUserBackImg(userInfo
												.getBgpic());
										loginInfo.setUserIdOld(userInfo
												.getOld_uid());
										loginInfo.setIsCertification(userInfo
												.getIsauth());
										loginInfo.setTick(userInfo
												.getTick());
										loginInfo.setLogin(true);
										loginInfo
												.setLoginState(LoginInfo.LOGIN);
										loginInfo.setSetUserName(true);
										loginInfo.setToken(entity.getBody()
												.getToken());
										Logger.i(TAG, "登录解析方法");
										loginInfo.saveInstance(context);
										Logger.i(TAG, "登录解析方法成功 了，下面便是handler");
										Message msg = handler.obtainMessage();
										msg.what = type;
										handler.sendMessage(msg);
									} else {
										Message msg = handler.obtainMessage();
										msg.what = typefail;
										handler.sendMessage(msg);
										ToastAlone.showToast(context, entity
												.getBody().getMessage(),
												Toast.LENGTH_SHORT);
									}

								} else {
									// toast(header.getMessage());
									Message msg = handler.obtainMessage();
									msg.what = typefail;
									handler.sendMessage(msg);
								}
							} else {
								Message msg = handler.obtainMessage();
								msg.what = typefail;
								handler.sendMessage(msg);
							}
						}

					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i(TAG, message);
						Message msg = handler.obtainMessage();
						msg.what = typefail;
						handler.sendMessage(msg);
					}
				});

		return;
	}

	/**
	 * 更新用户信息
	 * 
	 * @param context
	 * @param content
	 * @param type
	 */
	public void updataUserInfo(final Activity context, String content,
			final int type) {
		String url = V1VideoHttpApi.GET_EDIT_USER_INFO() + "&token="
				+ LoginInfo.getInstance().getToken() + "&devid="
				+ Constant.DEVICEID;
		Logger.i(TAG, "更新用户信息Url =" + url);
		ParamList list = new ParamList();
		if (type == 0) {// 昵称
			list.add(new Parameter("nickname", content));
		} else if (type == 1) {// 性别
			list.add(new Parameter("gender", content));
		} else if (type == 2) {// 个性签名
			list.add(new Parameter("signature", content));
		}

		RequestManager.getInstance().postRequest(context, url, list,
				LoginUserInfoEntity.class, 0, "PersonInfoActivity",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());
						LoginInfo loginInfo = LoginInfo.getInstance();
						if (object != null) {
							LoginUserInfoEntity entity = (LoginUserInfoEntity) object;
							com.v1.video.domain.BaseEntity.Header header = entity
									.getHeader();
							if (header == null) {
								ToastAlone.showToast(context, "未知错误",
										Toast.LENGTH_SHORT);
								return;
							} else if (!header.getStatus().equals("1")) {
								ToastAlone.showToast(context,
										header.getMessage(), Toast.LENGTH_SHORT);
								return;
							} else if (header.getStatus().equals("1")) {
								if (entity.getBody() != null) {

									if (entity.getBody().getStatus()
											.equals("1")
											|| entity.getBody().getData() != null) {
										UserInfo4_4 userInfo = entity.getBody()
												.getData();
										if (type == 0) {
											loginInfo.setNickname(userInfo
													.getNickname());
										} else if (type == 1) {
											loginInfo.setSex(userInfo
													.getGender());
										} else if (type == 2) {
											loginInfo.setDetail(userInfo
													.getSignature());
										}

										Logger.i(TAG, "登录解析方法");
										loginInfo.saveInstance(context);
									} else {
										ToastAlone.showToast(context, entity
												.getBody().getMessage(),
												Toast.LENGTH_SHORT);
									}

								} else {
									// toast(header.getMessage());
								}
							}
						}

					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i(TAG, message);
					}
				});
		return;
	}

	/**
	 * 上传头像
	 * 
	 * @param file
	 * @return
	 */
	public String sendUserImg(File file, int type) {
		String urlUserImg = V1VideoHttpApi.GET_EDIT_USER_HEAD() + "&token="
				+ LoginInfo.getInstance().getToken() + "&sign=" + type
				+ "&devid=" + Constant.DEVICEID;
		try {
			URL url = new URL(urlUserImg);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			// con.setRequestProperty("Content-Type",//ft_5.29修改成下面的流文件
			// "multipart/form-data;boundary="+boundary);
			con.setRequestProperty("Content-Type", "application/octet-stream");

			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());

			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(file);
			/* 设置每次写入1024bytes */
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
			}

			/* close streams */
			// fStream.close();
			ds.flush();
			fStream.close();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			/* 关闭DataOutputStream */
			ds.close();
			//
			String resJson = b.toString();
			// String resJson = new String(b,"UTF-8");
			Logger.i(TAG, "上传头像返回数据.jso=" + resJson);
			if (resJson != null && !resJson.equals("")) {
				Gson gson = new Gson();
				UserHeadModifyEntity info = gson.fromJson(resJson,
						UserHeadModifyEntity.class);
				if ((info.getBody().getData()).getStatus().equals("1")) {
					return info.getBody().getData().getUrl();
				}
			}
			return null;
			//
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * 忘记密码的 下发验证 码的短信
	 * 
	 * @param phoneNum
	 * @param password
	 */
	public void getVcode(final Activity context, final String phoneNum,
			String password, final Handler handler, final int succ,
			final int fail) {
		String key = Constant.getUserCheckKey(phoneNum);
		key = MD5.getMessageDigest(key);
		String url = V1VideoHttpApi.GET_VCODE_OF_FORGET() + "&devid="
				+ Constant.DEVICEID + "&key=" + key;

		Logger.i(TAG, "下发验证码的忘记密码Url =" + url);
		ParamList list = new ParamList();
		list.add(new Parameter("username", phoneNum));
		list.add(new Parameter("password", password));
		RequestManager.getInstance().postRequest(context, url, list,
				MyloginVcodeOfForgetEntity.class, 0, "Settingforget1Activity",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());

						if (object != null) {
							MyloginVcodeOfForgetEntity entity = (MyloginVcodeOfForgetEntity) object;
							com.v1.video.domain.BaseEntity.Header header = entity
									.getHeader();
							if (header == null) {
								// ToastAlone.showToast(SettingForget1Activity.this,
								// "未知错误", Toast.LENGTH_SHORT);
								if (handler != null) {
									Message msg = handler.obtainMessage();
									msg.what = fail;
									handler.sendMessage(msg);
								}
								return;
							} else if (!header.getStatus().equals("1")) {

								// ToastAlone.showToast(SettingForget1Activity.this,
								// header.getMessage(), Toast.LENGTH_SHORT);
								if (handler != null) {
									Message msg = handler.obtainMessage();
									msg.what = fail;
									handler.sendMessage(msg);
								}
								return;
							} else if (header.getStatus().equals("1")) {
								if (entity.getBody() != null) {
									if (entity.getBody().getData().getStatus()
											.equals("1")) {
										if (handler != null) {
											Message msg = handler
													.obtainMessage();
											msg.what = succ;
											handler.sendMessage(msg);
										}

									} else {
										ToastAlone.showToast(context, entity
												.getBody().getData()
												.getMessage(),
												Toast.LENGTH_SHORT);
										if (handler != null) {
											Message msg = handler
													.obtainMessage();
											msg.what = fail;
											handler.sendMessage(msg);
										}
									}

								} else {
									// toast(header.getMessage());
									if (handler != null) {
										Message msg = handler.obtainMessage();
										msg.what = fail;
										handler.sendMessage(msg);
									}
								}
							} else {
								if (handler != null) {
									Message msg = handler.obtainMessage();
									msg.what = fail;
									handler.sendMessage(msg);
								}
							}
						}

					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i(TAG, message);
						if (handler != null) {
							Message msg = handler.obtainMessage();
							msg.what = fail;
							handler.sendMessage(msg);
						}
					}
				});
	}
	
	/**
	 * 
	 * @param context
	 * @param czbm  操作编码 1. 点击广告 2. 曝光广告 
	 * @param czsx 广告位置 1.开机大图、2，首页焦点图,3.频道页专题位 、4.播放页广告位、5.首页及频道固定内容位 
	 * @param czjg  1 曝光成功，2.曝光失败 3.点击成功 4.点击失败 
	 */
	public void sendADVLogToServer(final Context context,String czbm,String czsx,String czjg){
		Logger.i(TAG, "sendADVLogToServer调用了");
		String url = "http://dc.v1.cn/log.html";
		ParamList list = new ParamList();
		list.add(new Parameter("ver", "1.0"));
		list.add(new Parameter("appver", Constant.PRODUCT_VERSION));
		list.add(new Parameter("devid", Constant.DEVICEID));
		list.add(new Parameter("czbm", czbm));
		list.add(new Parameter("czsx", czsx));
		list.add(new Parameter("czjg", czjg));
		Logger.i(TAG, "操作编码="+czbm+"广告位置="+czsx);
		String uid = "0";
		if(LoginInfo.getInstance().isLogin()){
			uid = LoginInfo.getInstance().getUserId();
		}
		list.add(new Parameter("uid", uid));
		list.add(new Parameter("time", ""+System.currentTimeMillis()));
		list.add(new Parameter("other", ""));
		list.add(new Parameter("pcode", Constant.PRODUCT_CODE));
		list.add(new Parameter("devtype", "2"));
		list.add(new Parameter("cid", ""));
		RequestManager.getInstance().getRequest(context, url, list,
				ResultInfoEntity.class, 0, "sendADVLogToServer", null);
	}
	
	public void askThirdADVLink(final Activity context,String url){
		RequestManager.getInstance().getRequest(context, url, null,
				ResultInfoEntity.class, 0, "askThirdADVLink", null);
	}
	
	public String getV1StarUserInfo(){
		Logger.i(TAG, "getV1StarUserInfo方法执行");
		String userInfo = "";
		try{
			File dir = new File(SDCardFileUtils.getSDCardPath()+Constant.v1_star_user_path);
			Logger.i(TAG, "dir.getpath=="+dir.getAbsolutePath());
			if(!dir.exists()){
				Logger.i(TAG, "目录为空");
				dir.mkdirs();
			}
			Logger.i(TAG, "目录不为空了");
			File cachedFile = new File(SDCardFileUtils.getSDCardPath()+Constant.v1_star_userinfo_path);
			if(cachedFile.exists()){
				Logger.i(TAG, "文件 存在");
				FileInputStream objFileUserInfo = new FileInputStream(cachedFile);
				int size = objFileUserInfo.available();
				byte []buffer = new byte[size];
				objFileUserInfo.read(buffer);
				objFileUserInfo.close();
//				InputStreamReader objFileUserInfo = new InputStreamReader(new FileInputStream(cachedFile));
				userInfo = new String(buffer, "UTF-8"); 
				Logger.i(TAG, "userInfo=="+userInfo);
			}else{
				Logger.i(TAG, "文件不存在");
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			return userInfo;
		}
	}
	
	/**
	 * 
	 * @param context
	 * @param handler
	 * @param userId
	 */
	public void getTheTick(final Activity context, final Handler handler,final int succ,final int fail) {
		
		String url = V1VideoHttpApi.GET_STAR_TICK_OF_USER() + "&devid="
				+ Constant.DEVICEID + "&uid=" + LoginInfo.getInstance().getUserId();

		Logger.i(TAG, "获取tickUrl =" + url);
		RequestManager.getInstance().getRequest(context, url, null,
				StarUserOfTickEntity.class, 0, ""+context,
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String key) {
						// TODO Auto-generated method stub
						Logger.i(TAG, "onSuccess.object=" + object.toString());

						if (object != null) {
							StarUserOfTickEntity entity = (StarUserOfTickEntity) object;
							com.v1.video.domain.BaseEntity.Header header = entity
									.getHeader();
							if (header == null) {
								// ToastAlone.showToast(SettingForget1Activity.this,
								// "未知错误", Toast.LENGTH_SHORT);
								if (handler != null) {
									Message msg = handler.obtainMessage();
									msg.what = fail;
									handler.sendMessage(msg);
								}
								return;
							} else if (!header.getStatus().equals("1")) {

								// ToastAlone.showToast(SettingForget1Activity.this,
								// header.getMessage(), Toast.LENGTH_SHORT);
								if (handler != null) {
									Message msg = handler.obtainMessage();
									msg.what = fail;
									handler.sendMessage(msg);
								}
								return;
							} else if (header.getStatus().equals("1")) {
								if (entity.getBody() != null) {
									if (entity.getBody().getData() != null) {
										LoginInfo.getInstance().setTick(entity.getBody().getData().getTick());
										if (handler != null) {
											Message msg = handler
													.obtainMessage();
											msg.what = succ;
											handler.sendMessage(msg);
										}

									} else {
										
										if (handler != null) {
											Message msg = handler
													.obtainMessage();
											msg.what = fail;
											handler.sendMessage(msg);
										}
									}

								} else {
									// toast(header.getMessage());
									if (handler != null) {
										Message msg = handler.obtainMessage();
										msg.what = fail;
										handler.sendMessage(msg);
									}
								}
							} else {
								if (handler != null) {
									Message msg = handler.obtainMessage();
									msg.what = fail;
									handler.sendMessage(msg);
								}
							}
						}

					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.i(TAG, message);
						if (handler != null) {
							Message msg = handler.obtainMessage();
							msg.what = fail;
							handler.sendMessage(msg);
						}
					}
				});
	}
}
